<template>
  <div class="cart-view container mx-auto py-6">
    <div class="cart-header mb-6">
      <h2 class="text-2xl font-bold text-gray-800 mb-1">我的购物车</h2>
      <p class="text-gray-600 text-sm">精选药品，品质保证</p>
    </div>

    <!-- 满减促销提示 -->
    <div
      v-if="activeFullReductions.length > 0"
      class="promotion-tips bg-gradient-to-r from-red-50 to-orange-50 rounded-lg p-4 mb-4 border border-red-200"
    >
      <div class="flex items-center mb-3">
        <div class="promotion-icon bg-red-500 rounded-full p-1.5 mr-2">
          <el-icon class="text-white" size="16"><PriceTag /></el-icon>
        </div>
        <h3 class="text-lg font-bold text-red-600">满减优惠活动</h3>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
        <div
          v-for="reduction in activeFullReductions"
          :key="reduction.billNo"
          class="bg-white rounded-lg p-3 border border-red-100 shadow-sm"
        >
          <h4 class="font-semibold text-gray-800 mb-2 text-sm">
            {{ reduction.promName }}
          </h4>
          <div class="space-y-1">
            <div
              v-for="detail in reduction.details"
              :key="detail.id"
              class="flex justify-between items-center text-xs bg-red-50 rounded p-1.5"
            >
              <span class="text-gray-700 font-medium"
                >满{{ formatPrice(detail.taxAmount, true) }}</span
              >
              <span class="font-bold text-red-600"
                >{{ Number(detail.dedRate) }}折</span
              >
            </div>
          </div>
          <div
            v-if="selectedTotalAmount >= getMinThreshold(reduction)"
            class="mt-2 text-xs text-green-600 font-medium bg-green-50 rounded p-1.5 text-center"
          >
            ✓ 已满足条件
          </div>
          <div v-else class="mt-2 text-xs text-orange-600 bg-orange-50 rounded p-1.5 text-center">
            还差{{ formatPrice(getMinThreshold(reduction) - selectedTotalAmount, true) }}即可享受优惠
          </div>
        </div>
      </div>
      <div
        v-if="bestDiscount"
        class="mt-4 p-3 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border border-green-200"
      >
        <div class="flex items-center justify-between">
          <span class="text-green-700 font-semibold"
            >当前最优折扣：{{ Number(bestDiscount.rate) }}折</span
          >
          <span class="text-green-600 font-bold"
            >立省{{ formatPrice(discountAmount, true) }}</span
          >
        </div>
      </div>
    </div>

    <!-- Cart Items - 紧凑表格布局 -->
    <div class="cart-items bg-white rounded-lg shadow-sm overflow-hidden border border-gray-200">
      <!-- Header -->
      <div class="cart-header bg-gray-50 px-4 py-3 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <el-checkbox
              v-model="selectAll"
              @change="handleSelectAll"
              size="default"
            />
            <span class="font-semibold text-gray-800">商品信息</span>
            <el-tag v-if="cartItems.length > 0" type="info" size="small">
              {{ cartItems.length }} 件
            </el-tag>
          </div>
          <el-button type="text" @click="clearCart" class="text-red-500 hover:text-red-700 text-sm">
            <el-icon class="mr-1"><Delete /></el-icon>
            清空
          </el-button>
        </div>
      </div>

      <!-- Empty State -->
      <div v-if="cartItems.length === 0" class="empty-cart py-12 text-center">
        <el-icon size="60" class="text-gray-300 mb-4"><ShoppingCartFull /></el-icon>
        <h3 class="text-lg font-semibold text-gray-600 mb-2">购物车是空的</h3>
        <p class="text-gray-500 mb-4">快去挑选您需要的药品吧！</p>
        <el-button type="primary" @click="$router.push('/products')">
          去购物
        </el-button>
      </div>

      <!-- Cart Items Table -->
      <div v-else class="cart-table">
        <div class="table-header hidden md:grid grid-cols-12 gap-3 px-3 py-1.5 bg-gray-50 border-b border-gray-100 text-xs font-medium text-gray-600">
          <div class="col-span-1 text-center">选择</div>
          <div class="col-span-5">商品信息</div>
          <div class="col-span-2 text-center">包装规格</div>
          <div class="col-span-1 text-center">数量</div>
          <div class="col-span-2 text-center">小计</div>
          <div class="col-span-1 text-center">操作</div>
        </div>

        <div class="table-body">
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item grid grid-cols-1 md:grid-cols-12 gap-3 px-3 py-2 border-b border-gray-100 hover:bg-gray-50 transition-colors"
            :class="{ 'bg-blue-50 border-blue-200': item.selected }"
          >
            <!-- 选择框 -->
            <div class="md:col-span-1 flex items-center justify-center">
              <el-checkbox
                v-model="item.selected"
                @change="(val: boolean) => handleItemSelect(item, val)"
                size="default"
              />
            </div>

            <!-- 商品信息 -->
            <div class="md:col-span-5 flex items-center space-x-2">
              <!-- 商品图片 -->
              <div class="flex-shrink-0 relative">
                <img
                  :src="item.goodsInfo.mainPic || '/images/no.jpg'"
                  :alt="item.goodsInfo.title"
                  class="w-12 h-12 object-cover rounded border border-gray-200"
                />
                <!-- 处方药标签 -->
                <div v-if="item.goodsInfo.isPres === 1" class="prescription-badge">
                  处方药
                </div>
              </div>

              <!-- 商品详情 -->
              <div class="flex-1 min-w-0">
                <h3 class="product-title font-medium text-gray-900 text-sm leading-tight mb-1 line-clamp-1">
                  {{ item.goodsInfo.title }}
                </h3>
                <div class="product-price mb-1">
                  <span class="text-base font-bold text-red-600">
                    {{ formatPriceAuth(item.goodsInfo.price || 0, !!userStore.token, userStore.userInfo?.discount, item.goodsInfo.noDiscounts) }}
                  </span>
                  <span v-if="userStore.userInfo?.discount && item.goodsInfo.noDiscounts !== 1" class="text-gray-500 text-xs ml-1 line-through">
                    {{ formatPriceAuth(item.goodsInfo.price || 0, !!userStore.token) }}
                  </span>
                  <span class="text-gray-500 text-xs ml-1">单价</span>
                </div>
                
                <!-- 基本信息 -->
                <div class="product-info text-xs text-gray-600 leading-tight">
                  <div class="flex items-center space-x-4">
                    <span class="truncate">{{ item.goodsInfo.goodsSpec }}</span>
                    <span class="truncate">{{ item.goodsInfo.manufacturer }}</span>
                    <div class="flex items-center space-x-1">
                      <span>库存:</span>
                                    <span :class="getStockStatusClass(item.goodsInfo.storNum)">
                {{ getStockStatusText(item.goodsInfo.storNum) }}
              </span>
                      <el-tag v-if="item.goodsInfo.isLowStock" type="danger" size="small" effect="light">
                        紧张
                      </el-tag>
                      <el-tag v-if="item.goodsInfo.nearestExpiredDate" type="warning" size="small" effect="light">
                        有效期：{{ formatDate(item.goodsInfo.nearestExpiredDate) }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 包装规格 -->
            <div class="md:col-span-2 flex items-center justify-center">
              <div class="text-center">
                <div class="space-x-1 mb-1">
                  <el-tag 
                    size="small" 
                    :type="item.goodsInfo.midpack > 1 ? 'success' : 'info'" 
                    effect="light"
                  >
                    {{ item.goodsInfo.midpack > 1 ? '中包装' : '件包装' }}
                  </el-tag>
                  <span v-if="item.goodsInfo.midpack > 1" class="text-xs text-gray-600">
                    {{ item.goodsInfo.midpack }}{{ item.goodsInfo.unit }}
                  </span>
                </div>
                <div v-if="item.goodsInfo.midpack > 1">
                  <el-tag 
                    size="small" 
                    :type="item.goodsInfo.isMidpackSaleDisabled === 0 ? 'success' : 'warning'"
                    effect="light"
                  >
                    {{ item.goodsInfo.isMidpackSaleDisabled === 0 ? '可拆零' : '不拆零' }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 数量控制 -->
            <div class="md:col-span-1 flex items-center justify-center">
              <div class="text-center">
                <el-input-number
                  v-model="item.count"
                  :min="item.goodsInfo.midpack > 1 && item.goodsInfo.isMidpackSaleDisabled === 1 ? item.goodsInfo.midpack : 1"
                  :max="Math.max(1, Number(item.goodsInfo.storNum))"
                  :step="item.goodsInfo.midpack > 1 && item.goodsInfo.isMidpackSaleDisabled === 1 ? item.goodsInfo.midpack : 1"
                  size="small"
                  @change="(val: number) => updateItemQuantity(item, val)"
                  class="quantity-input"
                />
                <div v-if="Number(item.goodsInfo.storNum) === 0 || item.count > Number(item.goodsInfo.storNum) || (item.goodsInfo.midpack > 1 && item.goodsInfo.isMidpackSaleDisabled === 1 && item.count % item.goodsInfo.midpack !== 0)" class="quantity-notes mt-0.5 text-xs text-center">
                  <p v-if="Number(item.goodsInfo.storNum) === 0" class="text-red-500">
                    暂无库存
                  </p>
                  <p v-else-if="item.count > Number(item.goodsInfo.storNum)" class="text-red-500">
                    库存不足
                  </p>
                  <p v-else-if="item.goodsInfo.midpack > 1 && item.goodsInfo.isMidpackSaleDisabled === 1 && item.count % item.goodsInfo.midpack !== 0" class="text-orange-600">
                    按{{ item.goodsInfo.midpack }}倍数
                  </p>
                </div>
              </div>
            </div>

            <!-- 小计 -->
            <div class="md:col-span-2 flex items-center justify-center">
              <div class="subtotal-price text-base font-bold text-red-600">
                {{ formatPriceAuth((Number(item.goodsInfo.price || 0) * item.count), !!userStore.token, userStore.userInfo?.discount, item.goodsInfo.noDiscounts) }}
                <span v-if="userStore.userInfo?.discount && item.goodsInfo.noDiscounts !== 1" class="text-gray-500 text-xs ml-1 line-through">
                  {{ formatPriceAuth((Number(item.goodsInfo.price || 0) * item.count), !!userStore.token) }}
                </span>
              </div>
            </div>

            <!-- 操作 -->
            <div class="md:col-span-1 flex items-center justify-center">
              <el-button 
                type="danger" 
                text 
                size="small"
                @click="deleteItem(item)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Summary Bar -->
    <div
      class="summary-bar bg-white rounded-lg shadow-sm p-4 flex justify-between items-center sticky bottom-4 z-10 border border-gray-200 mt-4"
    >
      <div class="flex items-center space-x-6">
        <el-checkbox
          v-model="selectAll"
          @change="handleSelectAll"
          size="default"
        >
          <span class="font-medium">全选</span>
        </el-checkbox>
        <div class="selected-info">
          <span class="text-gray-600">已选择</span>
          <span class="text-blue-600 font-bold text-lg mx-2">{{ selectedCount }}</span>
          <span class="text-gray-600">件商品</span>
        </div>
      </div>
      
      <div class="flex items-center space-x-6">
        <div class="price-summary text-right">
          <div class="total-info flex items-baseline space-x-2">
            <span class="text-gray-700">合计:</span>
            <span class="total-price text-2xl font-bold text-red-600">
              {{ formatPrice(finalPrice, true) }}
            </span>
          </div>
          <div v-if="userStore.userInfo?.discount" class="original-price text-sm text-gray-500 mb-1">
            原价: <span class="line-through">{{ formatPrice(selectedItems.reduce((sum: number, item: CartItem) => sum + Number(item.goodsInfo.price || 0) * item.count, 0), true) }}</span>
          </div>
          <div v-if="bestDiscount" class="discount-info text-sm text-green-600 mt-1">
            已享受{{ bestDiscount.rate }}折优惠，立省{{ formatPrice(discountAmount, true) }}
          </div>
        </div>
        
        <el-button
          type="danger"
          size="large"
          @click="checkout"
          :disabled="selectedCount === 0 || isCheckingOut"
          :loading="isCheckingOut"
          class="checkout-btn"
        >
          <span class="font-semibold">{{ isCheckingOut ? '生成中...' : '生成订单' }}</span>
        </el-button>
      </div>
    </div>

    <!-- 支付弹框 -->
    <PaymentDialog
      v-model:visible="paymentDialogVisible"
      :order-number="'CAR' + new Date().getTime()"
      :amount="finalPrice"
      @payment-success="handlePaymentSuccess"
      @payment-cancel="handlePaymentCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  PriceTag,
  Delete,
  ShoppingCartFull,
} from "@element-plus/icons-vue";
import PaymentDialog from "../components/PaymentDialog.vue";
import { useRouter } from "vue-router";
import { useCartStore } from "@/stores/cart";
import type { CartItem } from "@/types/cart";
import { useUserStore } from "@/stores/user";
import { promotionApi } from "@/api";
import type {
  FullReductionPromotion,
  FullReductionDetail,
} from "@/api/modules/promotion";
import { formatPrice, formatPriceAuth } from '@/lib/utils'
import { getStockStatusText, getStockStatusClass } from '@/lib/stockUtils'

const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();

// 格式化日期函数
function formatDate(dateString: string): string {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString
  }
}

// 满减促销数据
const fullReductions = ref<FullReductionPromotion[]>([]);

// 在组件挂载时获取购物车数据和满减促销
onMounted(() => {
  cartStore.fetchCartList();
  fetchFullReductions();
});

// 获取满减促销数据
async function fetchFullReductions() {
  try {
    const response = await promotionApi.getPromotionsByType("MJ");
    if (response.code === 1000 && response.data) {

      fullReductions.value = (response.data || []).filter(
        (p: any) => p.promType === "MJ" || p.promType === "满减"
      ) as FullReductionPromotion[];
    }
  } catch (error) {
    console.error("获取满减促销失败:", error);
  }
}

// 购物车商品列表
const cartItems = computed({
  get: () =>
    cartStore.cartItems.map((item) => ({
      ...item,
      selected: item.selected || false,
    })),
  set: (newItems) => {
    cartStore.cartItems = newItems;
  },
});

// 全选状态
const selectAll = computed({
  get: () =>
    cartItems.value.length > 0 &&
    cartItems.value.every((item) => item.selected),
  set: (value: boolean) => {
    const updatedItems = cartItems.value.map((item) => ({
      ...item,
      selected: value,
    }));
    cartItems.value = updatedItems;
  },
});

// 选中的商品
const selectedItems = computed(() =>
  cartItems.value.filter((item) => item.selected)
);

// 选中商品数量
const selectedCount = computed(() => selectedItems.value.length);

// 选中商品原始总价
const selectedTotalAmount = computed(() => {
  return selectedItems.value.reduce((sum, item) => {
    const price = Number(item.goodsInfo.price || 0)
    const count = item.count
    if (userStore.userInfo?.discount && item.goodsInfo.noDiscounts !== 1) {
      return sum + price * userStore.userInfo.discount * count
    }
    return sum + price * count
  }, 0)
})

// 活跃的满减促销（进行中的）
const activeFullReductions = computed(() => {
  const now = new Date();
  return fullReductions.value.filter((promotion) => {
    const startTime = new Date(promotion.startTime);
    const endTime = new Date(promotion.endTime);
    return promotion.status === 1 && now >= startTime && now <= endTime;
  });
});

// 获取满减促销的最小门槛
function getMinThreshold(reduction: FullReductionPromotion): number {
  if (reduction.details.length === 0) return 0;
  return Math.min(
    ...reduction.details.map((detail) => Number(detail.taxAmount))
  );
}

// 计算最优折扣
const bestDiscount = computed(() => {
  if (selectedTotalAmount.value === 0 || activeFullReductions.value.length === 0) {
    return null
  }

  let bestRate = 100 // 最优折扣率（100表示无折扣）
  let bestDetail: FullReductionDetail | null = null
  let bestBillNo: string | null = null

  // 遍历所有活跃的满减促销
  activeFullReductions.value.forEach((reduction) => {
    // 找到当前金额能享受的最优折扣
    const applicableDetails = reduction.details
      .filter((detail) => selectedTotalAmount.value >= Number(detail.taxAmount))
      .sort((a, b) => Number(a.dedRate) - Number(b.dedRate)) // 按折扣率升序排列，越小越优惠

    if (applicableDetails.length > 0) {
      const detail = applicableDetails[0] // 取最优惠的
      if (Number(detail.dedRate) < bestRate) {
        bestRate = Number(detail.dedRate)
        bestDetail = detail
        bestBillNo = reduction.billNo
      }
    }
  })

  return bestDetail
    ? { rate: bestRate, detail: bestDetail, billNo: bestBillNo || '' }
    : null
})

// 折扣金额
const discountAmount = computed(() => {
  if (!bestDiscount.value) return 0
  return selectedTotalAmount.value * (1 - bestDiscount.value.rate / 100)
})

// 最终价格（应用折扣后）
const finalPrice = computed(() => {
  return selectedTotalAmount.value - discountAmount.value
})

// 处理全选
function handleSelectAll(value: boolean) {
  const updatedItems = cartItems.value.map((item) => ({
    ...item,
    selected: value,
  }));
  cartItems.value = updatedItems;
}

// 更新商品数量
async function updateItemQuantity(item: CartItem, count: number) {
  const success = await cartStore.updateItemQuantity(Number(item.id), count);

  if (!success) {
    ElMessage.error("更新数量失败");
  }
}

// 删除商品
async function deleteItem(item: CartItem) {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品 "${item.goodsInfo.title}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const success = await cartStore.removeItem(Number(item.id));
    if (success) {
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
}

// 清空购物车
async function clearCart() {
  try {
    await ElMessageBox.confirm("确定要清空购物车吗？", "清空确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const success = await cartStore.clearCartItems();
    if (success) {
      ElMessage.success("清空成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("清空失败");
    }
  }
}

// 结算状态
const isCheckingOut = ref(false);

// 结算
async function checkout() {
  if (selectedCount.value === 0) {
    ElMessage.warning("请选择要结算的商品");
    return;
  }

  if (isCheckingOut.value) {
    return;
  }

  isCheckingOut.value = true;

  try {
    const selectedItems = cartItems.value.filter((item) => item.selected);
    const success = await cartStore.createOrderFromCart(
      selectedItems.map((item) => item.id),
      bestDiscount.value?.billNo
    );

    if (success === true) {
      ElMessage.success("订单生成成功");
      // 跳转到订单页面
      router.push("/my-orders");
    } else {
      ElMessage.error(`订单生成失败: ${success}`);
    }
  } catch (error) {
    console.error("生成订单失败:", error);
    ElMessage.error("生成订单失败，请重试");
  } finally {
    isCheckingOut.value = false;
  }
}

// 支付弹框状态
const paymentDialogVisible = ref(false);

// 处理支付成功
const handlePaymentSuccess = (paymentInfo: {
  orderNumber: string;
  paymentMethod: string;
}) => {
  ElMessage.success({
    message: `支付成功！使用${getPaymentMethodName(
      paymentInfo.paymentMethod
    )}，订单号: ${paymentInfo.orderNumber}`,
    duration: 3000,
  });

  // 清空已选择的购物车商品
  const updatedItems = cartItems.value.filter((item) => !item.selected);
  cartStore.cartItems = updatedItems;

  // 实际场景中应该跳转到订单页面
  setTimeout(() => {
    router.push("/my-orders");
  }, 1500);
};

// 处理支付取消
const handlePaymentCancel = (orderNumber: string) => {
  console.log(`取消支付订单: ${orderNumber}`);
};

// 获取支付方式名称
const getPaymentMethodName = (method: string): string => {
  const methodMap: Record<string, string> = {
    wechat: "微信支付",
    alipay: "支付宝支付",
    unionpay: "银联支付",
  };
  return methodMap[method] || method;
};

// 处理单个商品选中状态
function handleItemSelect(item: CartItem, selected: boolean) {
  const updatedItems = cartItems.value.map((cartItem) => {
    if (cartItem.id === item.id) {
      return {
        ...cartItem,
        selected,
      };
    }
    return cartItem;
  });
  cartItems.value = updatedItems;
}

</script>

<style scoped>
/* 整体布局 */
.cart-view {
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  min-height: 100vh;
}

/* 页面标题 */
.cart-header h2 {
  background: linear-gradient(135deg, #1f2937, #374151);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 促销提示区域 */
.promotion-tips {
  backdrop-filter: blur(10px);
  border: 1px solid rgba(239, 68, 68, 0.2);
}

.promotion-icon {
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

/* 购物车表格布局 */
.cart-table {
  font-size: 13px;
  line-height: 1.2;
}

.table-header {
  background: #f9fafb;
  font-weight: 600;
  color: #6b7280;
  min-height: 32px;
}

/* 购物车项目行 */
.cart-item {
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
  min-height: 60px;
  align-items: center;
}

.cart-item:hover {
  background: #f9fafb !important;
}

.cart-item.bg-blue-50 {
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  border-left-color: #3b82f6;
}

/* 处方药标签 */
.prescription-badge {
  position: absolute;
  top: -2px;
  left: -2px;
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  color: white;
  font-size: 8px;
  font-weight: 600;
  padding: 1px 4px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(220, 38, 38, 0.4);
  z-index: 10;
}

/* 商品标题 */
.product-title {
  color: #1f2937;
  cursor: pointer;
  transition: color 0.2s ease;
}

.product-title:hover {
  color: #3b82f6;
}

/* 商品价格 */
.product-price {
  display: flex;
  align-items: baseline;
  font-family: system-ui, -apple-system, sans-serif;
}

.product-price span:first-child {
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-weight: 700;
  letter-spacing: -0.025em;
}

/* 商品信息 */
.product-info {
  line-height: 1.2;
}

/* 商品图片 */
.cart-item img {
  flex-shrink: 0;
}

/* 处方药标签紧凑化 */
.prescription-badge {
  font-size: 7px;
  padding: 1px 3px;
}

/* 紧凑化整体间距 */
.cart-item .product-title {
  line-height: 1.3;
  margin-bottom: 2px;
}

.cart-item .product-price {
  margin-bottom: 2px;
}

/* 数量控制 */
.quantity-input :deep(.el-input-number) {
  width: 80px;
}

.quantity-input :deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d1d5db;
  transition: all 0.2s ease;
  height: 28px;
  padding: 0 8px;
}

.quantity-input :deep(.el-input__wrapper:hover) {
  border-color: #3b82f6;
}

.quantity-input :deep(.el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.quantity-input :deep(.el-input__inner) {
  height: 26px;
  line-height: 26px;
  font-size: 12px;
}

/* 小计价格 */
.subtotal-price {
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-family: system-ui, -apple-system, sans-serif;
  letter-spacing: -0.025em;
}

/* 空购物车状态 */
.empty-cart {
  border-radius: 12px;
}

/* 结算栏 */
.summary-bar {
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(226, 232, 240, 0.5);
}

.total-price {
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-family: system-ui, -apple-system, sans-serif;
  letter-spacing: -0.025em;
}

.checkout-btn {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%) !important;
  border: none !important;
  box-shadow: 0 2px 8px rgba(220, 38, 38, 0.3) !important;
  padding: 8px 24px !important;
  border-radius: 8px !important;
  transition: all 0.2s ease !important;
}

.checkout-btn:hover {
  background: linear-gradient(135deg, #b91c1c 0%, #991b1b 100%) !important;
  box-shadow: 0 4px 16px rgba(220, 38, 38, 0.4) !important;
  transform: translateY(-1px) !important;
}

.checkout-btn:disabled {
  background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%) !important;
  box-shadow: none !important;
  transform: none !important;
}

/* Element Plus 组件自定义 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #3b82f6;
}

:deep(.el-tag) {
  border-radius: 3px;
  font-weight: 500;
  font-size: 10px;
  padding: 1px 4px;
  height: 18px;
  line-height: 16px;
}

/* 行溢出文本省略 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-view {
    padding: 1rem;
  }
  
  .table-header {
    display: none;
  }
  
  .cart-item {
    grid-template-columns: 1fr;
    gap: 2;
    padding: 12px;
  }
  
  .cart-item > div {
    margin-bottom: 8px;
  }
  
  .summary-bar {
    flex-direction: column;
    gap: 1rem;
    position: relative;
  }
}

/* 简化动画 */
.cart-item {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 高亮选中状态 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border-color: #3b82f6;
}
</style>
